export const isNotNum = (val: string | null | number): boolean => {
  if (typeof val === 'string' && !isNaN(Number(val))) {
    return val.indexOf('.') < 0 && val.indexOf('0') == 0;
  } else {
    return isNaN(Number(val));
  }
};

export const transferAndToFixed = (num, length = 0) => {
  const str = num.toFixed(length).toString();
  const reg = str.indexOf('.') > -1 ? /(\d)(?=(\d{3})+\.)/g : /(\d)(?=(\d{3})+$)/g;
  return str.replace(reg, '$1,');
};

export const maxPlanDosage = (density: number, proportion: number, maxValue: number) => {
  if (isNotNum(density)) return 0;
  if (isNotNum(maxValue)) return 0;
  if (isNotNum(proportion)) return 0;

  let maxNum = 0;
  //密度（g/ml） * 占比 * 最大搅拌量（ml）
  maxNum =
    transferAndToFixed(Number(density), 4) *
    transferAndToFixed(Number(proportion), 4) *
    transferAndToFixed(Number(maxValue), 4);
  return transferAndToFixed(maxNum / 100, 4);
};

export const minPlanDosage = (density: number, proportion: number, minValue: number) => {
  if (isNotNum(density)) return 0;
  if (isNotNum(minValue)) return 0;
  if (isNotNum(proportion)) return 0;
  let minNum = 0;
  //密度（g/ml） *  占比 * 最小搅拌量（ml）
  minNum =
    transferAndToFixed(Number(density), 4) *
    transferAndToFixed(Number(proportion), 4) *
    transferAndToFixed(Number(minValue), 4);
  return transferAndToFixed(minNum / 100, 4);
};

const sumNum = (list: any[], field: string) => {
  let count = 0;
  list.forEach((item) => {
    if (Number(item[field])) {
      count += Math.round(item[field] * 100000000);
    }
  });
  return count / 100000000;
};

export const totalProportion = (list) => {
  const arr = list.filter((item) => item.proportion);
  return transferAndToFixed(sumNum(arr, 'proportion'), 2);
};
